package com.tangtang.basic.threads;

import java.util.Arrays;
import java.util.LinkedList;

public class MyQueue {
    private int QUEUE_MAX_SIZE = 100;
    private LinkedList<String> list = new LinkedList<>();

    public synchronized void add(String value){
        try {
            if(list.size()>=QUEUE_MAX_SIZE){
                wait();
            }
            list.add(value);
            notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized  String remove(){
        String result = null;
        try {
            if(list.size() == 0){
                wait();
            }
            result = list.removeFirst();
            notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    myQueue.add(finalI+"");
                }
            }).start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    myQueue.remove();
                }
            }).start();
        }



        System.out.println(Arrays.toString(myQueue.list.toArray()));
    }
}
